package datasource;

import entity.DataSourceProperty;
import javax.sql.DataSource;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.boot.jdbc.DataSourceBuilder;

/**
 * 数据源构建器
 */

public class DataSourceCreator implements BeanClassLoaderAware {

    private ClassLoader classLoader;

    public <T extends DataSource> T createDataSource(Class<? extends DataSource> dataSourceClass, DataSourceProperty dataSourceProperty) {
        DataSource dataSource = DataSourceBuilder.create(classLoader)
            .type(dataSourceClass)
            .url(dataSourceProperty.getUrl())
            .driverClassName(dataSourceProperty.getDriverClassName())
            .username(dataSourceProperty.getUsername())
            .password(dataSourceProperty.getPassword())
            .build();

        return (T) dataSource;
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }
}
